module API::V3
  class Wifis < Grape::API
    resource :wifis do
      params do
        requires :ip, type: String
        requires :account_id, type: Integer
      end
      post :login do
        error_code = 0

        account = Account.find_by_id(params[:account_id])
        if account.nil?
          message = "account doesn't exist"
          error_code = 1
        elsif WifiAccount.where(used: true).where(account_id: params[:account_id]).any?
          message = "account has been forzen"
          error_code = 2          
        else
          wifi_account = WifiAccount.avaliable.first
          if wifi_account.nil?
            message = "service temporarily unavailable"
            error_code = 3
          end
        end

        present :result, error_code == 0
        if error_code == 0
          wifi_account.update_attributes(used: true, used_or_released_at: Time.now, account_id: account.id)
          WifiLog.create(
            account_id: account.id, 
            wifi_account_id: wifi_account.id,
            mac: params[:mac],
            ip: params[:ip],
            imei: params[:imei],
            start_at: Time.now,
            last_seen: Time.now
          )
          present :account, wifi_account.username
          present :password, wifi_account.password
        else
          present :message, message
          present :error_code, error_code
        end        
      end

      params do
        requires :account_id, type: Integer
      end
      post :logout do
        wifi_account = WifiAccount.where(account_id: params[:account_id]).where(used: true).first
        if wifi_account
          wifi_account.update_attributes(used: false, accident: false, used_or_released_at: Time.now, account_id: nil)
        end

        wifi_log = WifiLog.where(account_id: params[:account_id]).where(end_at: nil).first
        if wifi_log
          wifi_log.update_attributes(end_at: Time.now, accident: false)
        end

        present result: true
      end

      params do
        requires :account_id, type: Integer
      end
      post :online do
        wifi_account = WifiAccount.where(account_id: params[:account_id]).where(used: true).first
        if wifi_account
          error_code = 0
          wifi_account.update_attributes(last_seen: Time.now)
        else
          error_code = 2
          message = "account doesn't exist or log in"
        end

        present :result, error_code == 0
        if error_code == 0
          present :avaliable, true
        else
          present :error_code, error_code
          present :message, message
        end
      end
    end
  end
end